package com.example.day26_toupinplayer;

import android.util.Log;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;

/**
 * Description:
 * Created by Gdu on 2021/1/5 9:32.
 */

public class SocketLive {
    private SocketCallback socketCallback;
    private int port;
    public static final String TAG = "SocketLive--";
    private MyWebsocketClient myWebsocketClient;

    public SocketLive(SocketCallback socketCallback, int port) {
        this.socketCallback = socketCallback;
        this.port = port;
    }

    public void start() {
        try {
            URI url = new URI("ws://192.168.31.57:12001");
            myWebsocketClient = new MyWebsocketClient(url);
            myWebsocketClient.connect();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private class MyWebsocketClient extends WebSocketClient{

        public MyWebsocketClient(URI serverUri) {
            super(serverUri);
        }

        @Override
        public void onOpen(ServerHandshake handshakedata) {
            Log.i(TAG,"onOpen");
        }

        @Override
        public void onMessage(String message) { }

        @Override
        public void onMessage(ByteBuffer bytes) {
            Log.i(TAG,"消息长度 "+bytes.remaining());
            byte[] buf = new byte[bytes.remaining()];
            bytes.get(buf);
            socketCallback.CallBack(buf);
        }

        @Override
        public void onClose(int code, String reason, boolean remote) {
            Log.i(TAG,"onClose "+reason);
        }

        @Override
        public void onError(Exception ex) {
            Log.i(TAG,"onErroe  "+ex.toString());
        }
    }

    public interface SocketCallback {
        void CallBack(byte[] data);
    }

}
